<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="filters.name" placeholder="名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="filters.userPhoneNumber" placeholder="持有人手机号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <org-unit-select v-if="isAdmin" v-model="filters.orgUnitId" placeholder="请选择店铺" :org-unit-type="1" />
      <el-radio-group v-model="filters.type" style="margin: 0 3px;">
        <el-radio-button :label="1" @click.native.prevent="typeFilter(1)">折扣券</el-radio-button>
        <el-radio-button :label="2" @click.native.prevent="typeFilter(2)">金额券</el-radio-button>
      </el-radio-group>
      <el-select v-model="filters.timeType" clearable placeholder="请选择时间类型">
        <el-option
          v-for="item in timeTypes"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <el-date-picker
        v-model="selectedDate"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        value-format="yyyy-MM-dd"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button v-if="canAddEntity" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleAdd">发放优惠券</el-button>
      <el-button v-if="false && canAddEntity" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleQRCode">二维码发放优惠券</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      border
      fit
      :height="tableHeight"
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="selsChange"
    >
      <el-table-column type="index" width="60" />
      <el-table-column prop="name" label="名称" min-width="180" />
      <el-table-column prop="orgUnitName" label="所属店铺" min-width="260" />
      <el-table-column prop="type" label="类型" width="70" :formatter="formatType" />
      <el-table-column prop="amount" label="额度" width="80" :formatter="formatAmount" />
      <el-table-column prop="movieLevelName" label="适用剧本类别" width="110" />
      <el-table-column prop="maxAmount" label="最大抵扣金额(元)" width="130" :formatter="formatMaxAmount" />
      <el-table-column prop="userNickname" label="持有人" width="120" />
      <el-table-column prop="userPhoneNumber" label="持有人手机号" width="110" />
      <el-table-column prop="createUserNickname" label="发放人" width="120" />
      <el-table-column prop="createUserPhoneNumber" label="发放人手机号" width="110" />
      <el-table-column prop="start" label="发放时间" width="155" />
      <el-table-column prop="end" label="失效时间" width="155" />
      <el-table-column prop="status" label="状态" width="80" :formatter="formatStatus" />
      <el-table-column label="操作" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="danger" size="small" @click="handleDelete(scope.index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="filters.page" :limit.sync="filters.limit" @pagination="loadPageList" />

    <!--新增界面-->
    <el-dialog title="优惠券信息" :visible.sync="addFormVisible" :close-on-click-modal="false" @close="qrcodeDialogClose">
      <el-form ref="addForm" :model="addForm" :label-width="formLabelWidth" :rules="addFormRules">
        <el-form-item label="优惠券定义" prop="couponDefinitionId">
          <coupon-definition-select v-model="addForm.couponDefinitionId" />
        </el-form-item>
        <el-form-item label="失效时间" prop="seconds">
          <el-radio-group v-model="addForm.seconds" style="margin: 0 3px;">
            <el-radio-button :label="-2">当天有效</el-radio-button>
            <el-radio-button :label="-3">本周有效</el-radio-button>
            <el-radio-button :label="-4">本月有效</el-radio-button>
            <el-radio-button :label="-5">本季度有效</el-radio-button>
            <el-radio-button :label="-6">本年有效</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="grantType===1" label="发放用户" prop="userId">
          <shop-player-select v-model="userId" />
        </el-form-item>
      </el-form>
      <div v-if="grantType===2 && qrcode.show" class="qr-code-container">
        <el-image fit="contain" :src="qrcode.codeUrl">
          <div slot="error" class="image-slot" />
        </el-image>
        <p>扫描二维码领取优惠券</p>
        <p>失效日期：{{ qrcode.expiredTime }}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button v-if="grantType===1" type="primary" :loading="addLoading" @click="addSubmit">提交</el-button>
        <el-button v-if="grantType===2" type="primary" :loading="qrcode.loading" @click="generateQrCode">生成二维码</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { saveCoupon, grantCoupon, loadCoupon, deleteCoupon, listCoupon } from '@/api/coupon'
import { qrCode } from '@/api/wx'
import OrgUnitSelect from '../components/org-unit-select'
import waves from '@/directive/waves' // waves directive
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import util from '@/utils/util.js'
import CouponDefinitionSelect from '@/views/components/coupon-def-select'
import ShopPlayerSelect from '@/views/components/shop-player-select'

export default {
  name: 'CouponDef',
  components: { ShopPlayerSelect, Pagination, OrgUnitSelect, CouponDefinitionSelect },
  directives: { waves },
  data() {
    return {
      selectedDate: null,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近30天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近90天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      timeTypes: [{
        value: 1,
        name: '发放时间'
      }, {
        value: 2,
        name: '使用时间'
      }
      ],
      tableHeight: 260,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      sels: [], // 列表选中列
      filters: {
        page: 1,
        limit: 20,
        name: '',
        orgUnitId: null,
        type: null,
        timeType: null
      },
      orderBy: {
        orderColumn: '',
        order: ''
      },

      // 新增界面是否显示
      addFormVisible: false,
      addLoading: false,
      addFormRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'blur' }]
      },
      // 新增界面数据
      recordId: 0,
      addForm: {
        couponDefinitionId: null,
        seconds: null,
        endTime: null
      },
      userId: null,
      grantType: null, // 发放方式,1:选择用户发放，2：二维码发放
      qrcode: {
        show: false,
        id: null,
        uuid: null,
        codeUrl: '',
        expiredTime: null
      },
      timer: null
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'formLabelWidth']),
    isAdmin() {
      const roles = this.userInfo.roles || []
      return roles.indexOf('Admin') !== -1
    },
    canAddEntity() {
      const roles = this.userInfo.roles || []
      if (roles.indexOf('Manager') !== -1) {
        if (this.userInfo.orgUnitType === 1) {
          // 店铺
          return true
        }
      }
      return roles.indexOf('ShopManager') !== -1
    },
    amountLabel() {
      return this.addForm.type === 1 ? '额度(%)' : '额度(元)'
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 220
    this.loadPageList()
  },
  methods: {
    formatType(row) {
      if (row.type === 1) {
        return '折扣券'
      } else if (row.type === 2) {
        return '金额券'
      } else {
        return '未知类型'
      }
    },
    formatAmount(row) {
      if (row.type === 1) {
        // 折扣券
        return row.amount + '%'
      } else {
        return util.currency.format(row.amount) + '元'
      }
    },
    formatMaxAmount(row) {
      if (row.type === 1) { // 折扣券才有最大抵扣金额
        if (row.maxAmount === -1) {
          return '无限制'
        }
        return util.currency.format(row.maxAmount)
      } else {
        return ''
      }
    },
    formatStatus(row) {
      if (row.status === 0) {
        return '未领取'
      } else if (row.status === 1) {
        return '未使用'
      } else if (row.status === 2) {
        return '部分使用'
      } else if (row.status === 3) {
        return '已使用'
      }
      return '未知状态'
    },
    loadPageList() {
      this.listLoading = true
      const param = { ...this.filters, ...this.orderBy }
      if (this.filters.timeType != null && this.selectedDate && this.selectedDate.length >= 2) {
        param.start = this.selectedDate[0]
        param.end = this.selectedDate[1]
      }
      listCoupon(param).then(({ success, message, data }) => {
        this.listLoading = false
        if (success) {
          const { records, total } = data || {}
          this.list = records
          this.total = total
        } else {
          this.$message({
            message: message || '查询列表失败',
            type: 'error'
          })
        }
      }, () => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.filters.page = 1
      this.loadPageList()
    },
    typeFilter(type) {
      if (type === this.filters.type) {
        this.filters.type = null
      } else {
        this.filters.type = type
      }
      this.handleFilter()
    },
    sortChange({ prop, order }) {
      this.orderBy.orderColumn = prop
      this.orderBy.order = order
      this.handleFilter()
    },
    selsChange(sels) {
      this.sels = sels
    },
    // 显示新增界面
    handleAdd: function() {
      this.grantType = 1
      this.addFormVisible = true
      this.userId = null
      this.addForm.couponDefinitionId = null
      this.addForm.endTime = null
      this.addForm.seconds = null
      this.qrcode.id = null
      this.qrcode.uuid = null
      this.qrcode.show = false
      this.qrcode.expiredTime = null
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    handleQRCode() {
      this.grantType = 2
      this.addFormVisible = true
      this.qrcode.codeUrl = ''
      this.addForm.couponDefinitionId = null
      this.addForm.endTime = null
      this.addForm.seconds = null
      this.qrcode.id = null
      this.qrcode.uuid = null
      this.qrcode.show = false
      this.qrcode.expiredTime = null
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    // 新增
    addSubmit: function() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            grantCoupon(this.userId, { ...this.addForm }).then(({ success, message }) => {
              this.addLoading = false
              if (success) {
                this.$message({
                  message: message || '提交成功',
                  type: 'success'
                })
                this.$refs['addForm'].resetFields()
                this.addFormVisible = false
                this.loadPageList()
              } else {
                this.$message({
                  message: message || '添加失败',
                  type: 'error'
                })
              }
            }, () => {
              this.addLoading = false
            })
          })
        }
      })
    },
    generateQrCode() {
      this.$confirm('确认生成二维码吗?', '提示', {
        type: 'warning'
      }).then(() => {
        saveCoupon({ ...this.addForm }).then(({ success, message, data }) => {
          if (success) {
            this.qrcode.show = true
            const { uuid, expiredTime, id } = data || {}
            this.qrcode.expiredTime = expiredTime
            this.qrcode.id = id
            this.qrcode.uuid = uuid
            this.closeMyTimer()
            this.timer = setInterval(this.timeoutRunner, 1000) // 每秒查询一下订单状态
            return uuid
          } else {
            this.$message({
              message: message || '生成二维码失败',
              type: 'error'
            })
            return null
          }
        }).then(uuid => {
          if (uuid) {
            qrCode({
              scene: uuid,
              page: 'pages/index/index',
              envVersion: 'develop',
              client: 1, // 玩家小程序领取优惠券
              width: 280
            }).then(res => {
              const blob = new Blob([res.data])
              this.qrcode.codeUrl = (window.URL || window.webkitURL).createObjectURL(blob)
            })
          }
        })
      })
    },
    timeoutRunner() {
      loadCoupon(this.qrcode.id).then(({ success, message, data }) => {
        if (success) {
          if (data.state === 1) { // 已领取
            this.$message({
              message: '领取成功',
              type: 'success'
            })
            this.qrcode.id = null
            this.chargeVisible = false
            this.loadPageList()
          } else if (data.state > 1) { // 已领取并使用,只是兼容,一般情况不会出现
            this.qrcode.id = null
            this.chargeVisible = false
          }
        } else {
          this.$message({
            message: message || '查询优惠券请求失败',
            type: 'error'
          })
        }
      })
    },
    qrcodeDialogClose() {
      this.closeMyTimer()
      if (this.qrcode.id) {
        deleteCoupon(this.qrcode.id).then(({ success, message }) => {
          if (success) {
            this.$message({
              message: message || '优惠券已删除',
              type: 'success'
            })
            this.chargeVisible = false
          } else {
            this.$message({
              message: message || '清除优惠券失败',
              type: 'error'
            })
          }
        })
      }
    },
    closeMyTimer() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    handleDelete(index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        deleteCoupon(row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.$message({
              message: message || '删除成功',
              type: 'success'
            })
            this.loadPageList()
          } else {
            this.$message({
              message: message || '删除失败',
              type: 'error'
            })
          }
        }, (res) => {
          this.listLoading = false
        })
      }).catch(() => {

      })
    }
  }
}
</script>

<style lang="scss" scoped>
.qr-code-container {
  text-align: center;
  img {
    display: inline-block;
  }
}
.image-slot {
  width: 100px;
  height: 100px;
}
</style>
